package com.fingard.dsp.bank.directbank.ccb04.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;

/**
 * Created by F on 2017/11/22.
 */
public class DESUtil {
    //DES加密算法
    public static byte[] desEncrypt(byte[] inputByteArray, byte[] DESkey) {
        try {
            //byte[] DESkey = inputKey.getBytes();// 设置密钥
            DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象

            Cipher enCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");// 得到加密对象Cipher
            enCipher.init(Cipher.ENCRYPT_MODE, key);// 设置工作模式为加密模式，给出密钥和向量
            byte[] pasByte = enCipher.doFinal(inputByteArray);
            return pasByte;
            /*BASE64Encoder base64Encoder = new BASE64Encoder();
            return base64Encoder.encode(pasByte);*/
        } catch (Exception e) {
            e.getMessage();
        }
        return null;
    }


    //DES解密算法
    public static byte[] desDecrypt(byte[] byteInputData, byte[] DESkey) {
        try {
            /*BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] byteInputData = base64Decoder.decodeBuffer(inputData);*/
            DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象

            // using DES in ECB mode
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte decryptedData[] = cipher.doFinal(byteInputData);
            //String value = new String(decryptedData, "UTF-8");
            return decryptedData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args){
        try {
            byte[] enData = desEncrypt("nihao".getBytes(), "12354678".getBytes());
            String deData = new String(desDecrypt(enData,"12354678".getBytes()));
            System.out.println("des加密:"+new String(enData));
            System.out.println("des解密:"+deData);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
